// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const {
	result_success,
	result_error
} = require('http-result-modle')
const db = uniCloud.database();
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;
module.exports = {
	_before: function() { // 通用预处理器

	},
	async alipayRequestCommon(alipayParams) {
		let app_id = alipayParams.app_id
		let url = alipayParams.url
		let biz_content = alipayParams.biz_content
		let params = alipayParams.params
		let appletInfoData = await db.collection('wmz-applet-info').doc(app_id).get()
		appletInfoData = appletInfoData.data[0]
		if (!appletInfoData) {
			return result_error('小程序数据获取失败')
		}
		let alipay_id = appletInfoData.alipay.app_id
		let access_token = appletInfoData.alipay.app_auth_token
		let app_private_key = appletInfoData.alipay.app_private_key
		const alipaySdk = new AlipaySdk({
			appId: alipay_id,
			privateKey: app_private_key
		});
		try {
			if(access_token){
				if (params) {
					params.appAuthToken = access_token
				} else {
					params = {
						appAuthToken: access_token
					}
				}
			}
			if (biz_content) {
				biz_content = JSON.stringify(biz_content)
				if (biz_content != "{}") {
					params.biz_content = biz_content
				}
			}
			const result = await alipaySdk.exec(url, params);
			if (!result.code || result.code === "10000") {
				return result_success(result)
			} else {
				return result_error(result.subMsg, result.code)
			}
		} catch (e) {
			console.log(e)
			return result_error('调用失败')
		}
		return result_error()
	}
}